#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pika
import json

# 建立连接
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.122.173'))
# 建立通道
channel = connection.channel()
# 1.声明队列
channel.queue_declare(queue='rpc_queue')


# 业务函数
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


# callback 回调函数：作为server端收到消息就要根据参数执行
def on_request(ch, method, props, body):
    n = json.loads(body)
    response = fib(n)
    ch.basic_publish(exchange='',
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id= \
                                                         props.correlation_id),
                     body=str(response))
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=1)
# 2.监听rpc_queue 毁掉函数on_request
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)
# 开始监听
print(" [x] Awaiting RPC requests")
channel.start_consuming()
